import {useState} from "react";
import {useImmer} from "use-immer";

const UseImmerPage = () => {

  /**
   * 页面说明：
   * 1. 使用useState修改复杂类型的。eg：嵌套的对象。
   */

  const [userInfo1, setUserInfo1] = useState({
    name: '开水',
    age: 20,
    hobby: {
      name: '玩',
      time: 2,
      place: '家'
    }
  })
  const handleChangeHobbyName1 = () => {
    /*setUserInfo1({
      ...userInfo1,
      hobby: {
        ...userInfo1.hobby,
        name: '游泳',
      }
    })*/

    // 这样也可以的
    const tempObj = {...userInfo1};
    tempObj.hobby.name = '吃饭'
    setUserInfo1(tempObj)
  }

  const [userInfo2, setUserInfo2] = useImmer({
    name: '开水',
    age: 20,
    hobby: {
      name: '玩',
      time: 2,
      place: '家'
    }
  })
  const handleChangeHobbyName2 = () => {
    setUserInfo2(draft => {
      draft.name += '~'
      draft.hobby.name = '睡觉'
    })
  }

  const [userList, setUserList] = useImmer([
    {name: '张三', age: 20, id: 1, score: 11,},
    {name: '李四', age: 21, id: 2, score: 12,},
  ])
  const handleAdd = () => {
    setUserList(draft => {
      draft.push({
        name: '赵武', age: 22, id: Math.random(), score: 13
      })
    })
  }
  const handleDelete = () => {
    setUserList(draft => {
      draft.splice(0,1)
    })
  }
  const handleEdit = () => {
    setUserList(draft => {
      draft[0].name += '~'
    })
  }

  /**
   * 基本类型：
   */
  const [isLoading, setIsLoading] = useImmer(false)
  const handleChangeLoading = () => {
    setIsLoading(!isLoading)
  }
  return (
    <>
      <div>userImmer</div>
      <div>

        <h2>useState实现复杂类型</h2>
        <div>名字：{userInfo1.name}</div>
        <div>年龄：{userInfo1.age}</div>
        <div>爱好：{userInfo1.hobby.name}</div>
        <div>地址：{userInfo1.hobby.place}</div>

        <button onClick={handleChangeHobbyName1}>修改爱好</button>
        <hr/>
      </div>

      <div>
        <h2>useImmer实现复杂类型</h2>
        <div>名字：{userInfo2.name}</div>
        <div>年龄：{userInfo2.age}</div>
        <div>爱好：{userInfo2.hobby.name}</div>
        <div>地址：{userInfo2.hobby.place}</div>

        <button onClick={handleChangeHobbyName2}>修改爱好</button>
        <hr/>
      </div>

      <div>
        <h2>数组</h2>
        {
          userList.map((item, index) => {
            return (
              <div key={item.id}>
                <span>名字：{item.name}</span>   &nbsp; &nbsp; &nbsp; &nbsp;
                <span>年龄：{item.age}</span> &nbsp; &nbsp; &nbsp; &nbsp;
                <span>分数：{item.score}</span> &nbsp; &nbsp; &nbsp; &nbsp;
              </div>
            )
          })
        }

        <button onClick={handleAdd}>添加一行内容</button>
        <button onClick={handleDelete}>删除一行内容</button>
        <button onClick={handleEdit}>修改</button>
      </div>
      <hr/>
      <div>
        <h2>基本类型</h2>
        <div>{isLoading? '加载中...': '加载完成！'}</div>

        <button onClick={handleChangeLoading}>切换状态</button>
      </div>
    </>
  )
}

export default UseImmerPage;
